/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

angular.module('app', ['ngCordova']).controller('mainController', function ($scope, $cordovaInAppBrowser, $cordovaFile, $cordovaFileTransfer, $q, $cordovaFileOpener2) {
    /**
     * 在浏览器上阅读pdf
     * 使用插件:
     * cordova plugin add cordova-plugin-inappbrowser
     */
    var url = 'http://192.168.202.216:8088/test.pdf';
    $scope.readPdfInBrowser = function () {
        var defaultOptions = {
            location: 'no',
            clearcache: 'no',
            toolbar: 'yes'
        };
        $cordovaInAppBrowser.open(url, '_blank', defaultOptions)
            .then(function (event) {
                // success
                console.log('success');
                console.log(event);
            })
            .catch(function (event) {
                // error
                console.log('error');
                console.log(event);
            });
    };
    /**
     * 从服务器上下载pdf
     * 然后再用软件打开
     * 使用插件:
     * cordova plugin add cordova-plugin-file
     * cordova plugin add cordova-plugin-file-transfer
     * cordova plugin add cordova-plugin-file-opener2
     */
        // 存放下载文件的目录
    var localDirName = 'LinkCRM';
    $scope.readPdfLocal = function () {
        var fileName = 'test.pdf';
        var filePath = '';
        // 获取设备信息,判断是ios或android
        var platform = getPlatform();
        if (platform === 'android') {
            filePath = cordova.file.externalRootDirectory + localDirName + "/";
            // 安卓会有写入设备存储权限问题:
            // WRITE_EXTERNAL_STORAGE
        } else if (platform === 'iphone') {
            filePath = cordova.file.tempDirectory + localDirName + "/";
        }

        checkPermission(platform).then(function () {
            // 检查文件是否在本地存在
            // filePath = filePath.replace("file:///", "/");
            console.log(filePath + fileName);
            $cordovaFile.checkFile(filePath, fileName).then(function (success) {
                console.log(success);
                // 文件存在,直接预览
                openPdf(filePath + fileName);
            }, function (error) {
                // 文件不存在
                // 下载文件
                downloadFile(url, filePath, fileName).then(function (filePathName) {
                    openPdf(filePathName);
                });
            });
        }, function (error) {
            console.log(error);
        });
    };

    function checkPermission(platform) {
        var defer = $q.defer();
        if (platform === 'android') {
            // 安卓需要检测权限
            var permissions = cordova.plugins.permissions;
            // 写入存储设备权限
            permissions.checkPermission(permissions.WRITE_EXTERNAL_STORAGE, function (checkSuccess) {
                console.log(checkSuccess);
                // 没有权限,则申请权限
                if (!checkSuccess.hasPermission) {
                    permissions.requestPermission(permissions.WRITE_EXTERNAL_STORAGE, function (requestSuccess) {
                        console.log(requestSuccess);
                        defer.resolve();
                    }, function (requestError) {
                        console.log(requestError);
                        defer.reject(requestError);
                    });
                } else {
                    defer.resolve();
                }
            }, function (checkError) {
                console.log(checkError);
                defer.reject(checkError);
            });
        } else if (platform === 'iphone') {
            // ios 无需检测
            defer.resolve();
        }
        return defer.promise;
    }

    function downloadFile(downloadUrl, filePath, fileName) {
        var fileTransfer = new FileTransfer();
        downloadUrl = encodeURI(downloadUrl);
        var defer = $q.defer();
        checkDir(filePath).then(function (fileEntry) {
            // 文件最终保存路径(带文件名)
            var saveFilePath = encodeURI(fileEntry.nativeURL + fileName);
            console.log(saveFilePath);
            fileTransfer.download(
                downloadUrl,
                saveFilePath,
                function (entry) {
                    // 下载完成
                    console.log('下载完成');
                    console.log(entry);
                    // 将当前文件路径返回
                    defer.resolve(entry.toURL());
                },
                function (error) {
                    // 下载失败
                    console.log('下载失败');
                    console.log(error);
                },
                false,
                {
                    headers: {}
                }
            );
            // 获取下载进度
            fileTransfer.onprogress = function (progressEvent) {
                if (progressEvent.lengthComputable) {
                    console.log(progressEvent.loaded / progressEvent.total);
                } else {
                    loadingStatus.increment();
                }
            };

        }, function (error) {
            console.log(error);
        });
        return defer.promise;
    }

    /**
     * 检查文件夹是否存在
     * @param filePath
     * @returns {*|null|d}
     */
    function checkDir(filePath) {
        var defer = $q.defer();
        // filePath = filePath.replace("file:///", "/").replace(localDirName,'');
        filePath = filePath.replace(localDirName, '');
        console.log(filePath);
        $cordovaFile.checkDir(filePath, localDirName)
            .then(function (success) {
                // 文件夹已经存在,无需创建
                console.log(success);
                defer.resolve(success);
            }, function (error) {
                // 文件夹不存在,创建文件夹
                createNewDir(filePath).then(function (fileEntry) {
                    // 创建成功
                    defer.resolve(fileEntry);
                }, function (error) {
                    console.log(error);
                    defer.reject(error);
                });
            });
        return defer.promise;
    }

    /**
     * 创建文件夹
     * @param filePath
     * @returns {*|null|d}
     */
    function createNewDir(filePath) {
        var defer = $q.defer();
        $cordovaFile.createDir(filePath, localDirName, false)
            .then(function (success) {
                console.log(success);
                //该文件夹的路径
                console.log("创建文件夹成功!路径:" + success.nativeURL);

                defer.resolve(success);
            }, function (error) {
                // error
                console.log("创建文件夹失败!");
                defer.reject(error);
            });
        return defer.promise;
    }

    function openPdf(filePath) {
// 这里只能打开pdf,限制文件类型
        $cordovaFileOpener2.open(
            filePath,
            'application/pdf'
        ).then(function (success) {
            console.log(success);
        }, function (err) {
            console.log(err);
        });
    }

    function getPlatform() {
        var ua = navigator.userAgent.toLowerCase();
        var platform = '';
        if (/(micromessenger)/i.test(ua)) {
            platform = 'weixin';
        } else if (/(iphone)/i.test(ua)) {
            // ipad pro上会检测成iPhone,所以再加一个判断,其他pad设备仍旧走下面代码
            if (navigator.platform === 'iPad') {
                platform = 'ipad';
            } else {
                platform = 'iphone';
            }
        } else if (/(ipad)/i.test(ua)) {
            platform = 'ipad';
        } else if (/(android)/i.test(ua)) {
            platform = 'android';
        } else {
            platform = 'web';
        }
        return platform;
    }
});